iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0
Mobile Development

從零開始學習 iOS系列 第 22

從零開始學習 iOS Day21 - Push Notification

  • 分享至 

  • xImage
  •  

App 不只是被動等使用者打開,有時候我們希望主動提醒使用者有新內容或事件,這就是 Push Notification(推播通知) 的任務。

今天我們就要來介紹 iOS 的通知機制,包含:

  • Local Notification(本地通知)
  • Remote Notification(遠端推播 / APNs)

什麼是 Push Notification

推播通知是 App 與使用者之間的溝通橋樑,用途包含:

  • 提醒事件(行事曆、待辦、更新)
  • 提示有新內容(新聞、訊息、優惠)
  • 執行背景更新(靜默通知)

在 iOS 中主要分成兩種

  • Local Notification:由 App 本地排程觸發,不需要網路。
  • Remote Notification:從伺服器經由 APNs 發送。

Local Notification 實作

權限申請

要使用通知,第一步就是向使用者申請授權。

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]){ granted, error in
    if granted {
        print("使用者允許通知")
    } else {
        print("使用者拒絕通知")
    }
}
  • options:表示顯示通知的方式有圖文、聲音。另外還有像 criticalAlert(緊急通知)或 CarPlay 等選項可用。

https://github.com/jian-fu-hung/ithelp-2025/blob/main/image/Day21/%E6%88%AA%E5%9C%96%202025-10-06%20%E6%99%9A%E4%B8%8A9.37.58.png?raw=true

發送通知

例如:3 秒後顯示一則通知。

func sendLocalNotification() {
    let content = UNMutableNotificationContent()
    content.title = "提醒你一下 📣"
    content.body = "該回來繼續學 Swift 鐵人賽囉!"
    content.sound = .default

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
    let request = UNNotificationRequest(identifier: "SwiftDay20", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request)
}

https://github.com/jian-fu-hung/ithelp-2025/blob/main/image/Day21/%E6%88%AA%E5%9C%96%202025-10-06%20%E6%99%9A%E4%B8%8A9.42.10.png?raw=true

  • timeInterval:表示三秒後顯示。
  • repeats:表示是否重複發送。
  • identifier:表示此通知的唯一值,如果後續有推播也是用此identifier,則覆蓋掉原本的。

前景顯示推播

預設情況下,App 在前景時不會顯示通知

要讓通知在前景時也能彈出,我們可以實作 delegate:

import SwiftUI
import UserNotifications

class NotificationManager: NSObject, ObservableObject, UNUserNotificationCenterDelegate {
    override init() {
        super.init()
        // 註冊通知權限
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
            if granted {
                print("使用者允許通知")
            } else {
                print("使用者拒絕通知")
            }
        }
        // 指定 delegate
        UNUserNotificationCenter.current().delegate = self
    }
    
    // 實作前景通知顯示
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // App 在前景時也顯示通知
        completionHandler([.banner, .sound])
    }
    
    // 發送通知
    func sendLocalNotification() {
        let content = UNMutableNotificationContent()
        content.title = "提醒你一下"
        content.body = "該回來繼續學 Swift 鐵人賽囉!"
        content.sound = .default

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
        let request = UNNotificationRequest(identifier: "SwiftDay20", content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().add(request)
    }
}

Remote Notification 介紹

由於沒有 Apple Developer 帳號,我們先簡單介紹原理。

APNs 是什麼?

APNs(Apple Push Notification Service) 是 Apple 官方的推播服務平台。所有發送到 iPhone、iPad、Mac 的推播,都必須經過 APNs。

Remote Notification的流程如下:

你的伺服器 → APNs → 使用者的 iPhone → 顯示通知

遠端推播必要項目

  1. 申請 Apple Developer 帳號(需付費)
  2. 啟用 Push Notification 能力
  3. 上傳推播憑證(或使用 Key)
  4. App 向 APNs 註冊並取得 Device Token

(你的伺服器端就能用這個 Token 發送推播)


今日小結

今天我們學到:

  • Local Notification:App 內自行排程的通知,無需網路
  • Remote Notification:由伺服器經 APNs 傳送的推播
  • 授權申請前景顯示設定的重點

上一篇
從零開始學習 iOS Day20 - Swift 資料儲存基礎
下一篇
從零開始學習 iOS Day22 - Push Notification II
系列文
從零開始學習 iOS24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言